package com.fingard.dsp.bank.directbank.payfree01;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.util.HashMap;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RefundState;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.SplitHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;

public class PAYFREE01Statement extends PAYFREE01Base implements IStatement {
	@Override
	public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
		RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        String[] tmpPosRecRespHeader = null;
        String tmpPosMode = getBankConfig().getValueAsString("posRecUseVersion");
        if ("A".equals(tmpPosMode) && "S".equals(p_reqQrySttm.statementType)) {
        	tmpPosRecRespHeader = getPosRecStatement(p_reqQrySttm, retAts);
        }
        String tmpPosRecTotalNum = retAts.totalNum;
        
        String[] tmpSinglePayHeader = null;
        if ("A".equals(tmpPosMode) && "S".equals(p_reqQrySttm.statementType)) {
        	tmpSinglePayHeader = getWirePosRecStatement(p_reqQrySttm, retAts);
        }
        String tmpSinglePayTotalNum = retAts.totalNum;
       
        if (retAts.getWrittenRdCount() == 0) {
        	if ("-1".equals(tmpPosRecRespHeader[0]) && "-1".equals(tmpSinglePayHeader[0])) {
	            retAts.writeRespCode("-1");
	            retAts.writeRespInfo(tmpPosRecRespHeader[1]+","+tmpSinglePayHeader[1]);
	        } else {
	        	retAts.writeRespCode("0");
				retAts.writeRespInfo("交易为空");
	        }
		} else {
			retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(tmpPosRecTotalNum) + Integer.parseInt(tmpSinglePayTotalNum)));
		}

        retAts.writeEnd();
        return retAts;
	}

	private String[] getPosRecStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] respHeader = new String[]{"",""};
		
		String respCode = "";
		String respInfo = "";
		
		retAts.totalNum = "0";
		int totalNum = 0;
		
		try {
			FtpSet ftpSet = bankFront.getFtpSet("pos");

            ftpSet.downDir = StringHelper.trimEnd(ftpSet.getDownDir("pos"), "/") + "/" + p_reqQrySttm.busDate;


			WriteBankLogLn2("深银联POS对账单FTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);
			
			StringBuilder sbFileContent = new StringBuilder();
			String downFileName = getBankConfig().getValueAsString("merchantId") + p_reqQrySttm.busDate + "001.txt";
			WriteBankLogLn2("深银联POS对账单所在服务器路径:" + ftpSet.downDir + "/" + downFileName);
			
			String localFilePath = createTempFileDirectory() + File.separator + downFileName;
            WriteBankLogLn2("深银联POS对账单保存本地路径:" + localFilePath);
            
            FtpReceiver ftpReceiver = null;
			String posRecRequestType = getBankConfig().getValueAsString("posRecRequestType");
			if ("ftp".equals(posRecRequestType.toLowerCase())) {
				FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
	            ftpReceiver = ftpPortClient.downloadFile(downFileName, localFilePath);
			} else if ("sftp".equals(posRecRequestType.toLowerCase())) {
				SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
				String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + downFileName;
				WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
				ftpReceiver = sftpPortClient.downloadFile("",sftpFilePath, localFilePath);
			}
            if (ftpReceiver.isCompleted) {
            	if (sbFileContent.length() > 0) {
            		sbFileContent.append("\n");
            	}
            	sbFileContent.append(FileHelper.readFileText(localFilePath, getCharset("UTF-8", "pos")));
            } else {
            	respCode = "-1";
    			respInfo = "深银联POS对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
            }
//            sbFileContent.append(FileHelper.readFileText(localFilePath, getCharset("UTF-8", "pos")));
			if (StringHelper.hasAnyChar(sbFileContent.toString())) {
				String tmpStrRet = sbFileContent.toString();
				WriteBankLogLn2("深银联POS对账单响应数据:\r\n" + tmpStrRet);
				
				respCode = "0";
				
				StringReader strReader = new StringReader(tmpStrRet);
				BufferedReader tmpReader = new BufferedReader(strReader);
				
				boolean isContinue = false;
				while(true) {
					String eachline = tmpReader.readLine();
					if(eachline == null){
						break;
					}
                    if ("".equals(eachline)) {
                        continue;
                    }
					String[] detailNodes = eachline.split("`~");
					if (p_reqQrySttm.actNum.equals(detailNodes[1].trim())) {
						totalNum++;
						isContinue = true;
						RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
						
						if (StringHelper.hasAnyChar(detailNodes[4])) {
							tmpRetDetail.askNumber = detailNodes[4].trim();
						}
						
						tmpRetDetail.cdFlag = "22";
						
						if (StringHelper.hasAnyChar(detailNodes[11])) {
							tmpRetDetail.amount = StringHelper.amountDivide100(detailNodes[11].trim());
						}
						
						if (StringHelper.hasAnyChar(detailNodes[15])) {
							tmpRetDetail.fee = StringHelper.amountDivide100(detailNodes[15].trim());
						}
						
						tmpRetDetail.busTime = detailNodes[6];
						
						if (StringHelper.hasAnyChar(detailNodes[7])) {
							tmpRetDetail.oppAct = detailNodes[7].trim();
						}
						
						if (StringHelper.hasAnyChar(detailNodes[8])) {
							tmpRetDetail.oppActName = detailNodes[8].trim();
						}
						
						if ("2".equals(detailNodes[13].trim())) {
							tmpRetDetail.transState = TransState.Success;
						} else {
							tmpRetDetail.transState = TransState.Fail;
						}
	    				
		        		retAts.writeRetDetail(tmpRetDetail);
					}
				}
				
				if (!isContinue) {
					respCode = "0";
					respInfo = "没有符合条件的记录!";
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			respCode = "-1";
			respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.totalNum = String.valueOf(totalNum);
		
		respHeader[0] = respCode;
		respHeader[1] = respInfo;
		
		return respHeader;
	}
	
	public String[] getWirePosRecStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] respHeader = new String[]{"",""};
		
		String respCode = "";
		String respInfo = "";
		
		retAts.totalNum = "0";
		int totalNum = 0;

		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
			if (actItem == null) {
				respHeader[0] = "-1";
				respHeader[1] = "未找到账号" + p_reqQrySttm.actNum + "商户配置信息!";
				return respHeader;
			}
			
			String ftpHost = getBankConfig().getMapValueByKey("ftpMapping", "ftpHost");
			int ftpPort = Integer.parseInt(getBankConfig().getMapValueByKey("ftpMapping", "ftpPort"));
			
			String ftpUserName = getBankConfig().getMapValueByKey("ftpMapping", "ftpUserName");
			String ftpPassword = getBankConfig().getMapValueByKey("ftpMapping", "ftpPassword");
			
			String ftpPath = actItem.ftpPath;
			String localPath = getBankConfig().getMapValueByKey("ftpMapping", "localPath");
			
			String fileName = "";
			if (ftpPath.contains("jiankang")) {
				fileName = actItem.inMerchantId + Format.Date6Format.format(p_reqQrySttm.getBusDate()) + ".TXT"; /* 健康险 */
			} else {
				fileName = actItem.inMerchantId + "_" + Format.Date6Format.format(p_reqQrySttm.getBusDate()) + ".TXT"; /* 产险、寿险 */
			}
			
			WriteBankLogLn2("待下载FTP文件路径: " + ftpPath + fileName);
			WriteBankLogLn2("文件保存至本地路径: " + localPath + File.separator + fileName);
			
			FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);
			
			String filePath = localPath + File.separator + fileName;
			String ftpFileContent = FtpUtil.getTextFromFile(filePath, "GBK");

			if (ftpFileContent.length() == 0) {
				respHeader[0] = "-1";
				respHeader[1] = "本日无交易";
				return respHeader;
			}

			WriteBankLogLn2("对账单文件内容: \r\n" + ftpFileContent);
	        
	        String[] totalLine = ftpFileContent.split("\r\n");
	        if (totalLine.length > 1) {
	        	int endIndex = totalLine[0].lastIndexOf("总金额");
	        	totalNum = Integer.parseInt(totalLine[0].substring(4, endIndex).trim());
	        	
	        	int detailIndex = ftpFileContent.indexOf("流水号");
	        	String detailContent = ftpFileContent.substring(detailIndex);
	        	
	        	StringReader strReader = new StringReader(detailContent);
				BufferedReader tmpReader = new BufferedReader(strReader);
				
				tmpReader.readLine();
				String[] columns = new String[]{"流水号","终端号","交易识别号","交易日期","金额","清算账号","交易类型"};
				
				String line = "";
				while((line = tmpReader.readLine()) != null) {
					String eachline = line.trim();
					if(eachline == null) {
						retAts.writeRespCode("-1");
						retAts.writeRespInfo("本日或本月无收支");

						break;
					} else {
						if ("".equals(eachline)) {
							continue;
						}
						
						String[] values = eachline.split("\\|");
						if(columns.length == values.length){
							HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);
							RetAtsStatementDetail retDetail = new RetAtsStatementDetail();
							
							if(mapKV.containsKey("交易日期")){
								retDetail.busTime = mapKV.get("交易日期").trim()+"000000";
							}
							
							if(mapKV.containsKey("交易类型")){
								retDetail.busType = mapKV.get("交易类型").trim();
							}
							
							if(mapKV.containsKey("交易识别号")){
								retDetail.askNumber = mapKV.get("交易识别号").trim();
							}
							
							if(mapKV.containsKey("金额")){
								retDetail.amount = mapKV.get("金额").trim();
							}
							
							if(mapKV.containsKey("终端号")){
								retDetail.termCode = mapKV.get("终端号").trim();
							}
							
							retDetail.transState = TransState.Success;
							retDetail.refundState = RefundState.Exception;
							
							retAts.writeRetDetail(retDetail);
						} else {
							break;
						}
					}
				}
	        } else {
	        	respCode = "-1";
	        	respInfo = "返回结果不符合预期!";
	        }
		} catch (Exception e) {
			e.printStackTrace();
			respCode = "-1";
			respInfo = e.getMessage();
			WriteBankLogLn(e);
		}
		
		retAts.totalNum = String.valueOf(totalNum);
		
		respHeader[0] = respCode;
		respHeader[1] = respInfo;
		
		return respHeader;
	}
}
